package edu.hawaii.ics414;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/**
 * Initializes the search results screen for viewing search results.
 * 
 * @author Matthew Mizumoto
 * 
 */

public class SearchResults extends Activity {

  /*
   * Called when the activity is first created.
   */
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.search_result_view);

    Intent intent = getIntent();
    String gameName = intent.getStringExtra("gameName");
    String[] games;
    ArrayList<String> results = new ArrayList<String>();
    ListView listView = (ListView) findViewById(R.id.ResultList);

    try {
      games = new GetSearchResults().execute(gameName).get(5, TimeUnit.SECONDS);
      if (games.length > 0) {
        for (int i = 0; i < games.length; i++) {
          results.add(games[i].trim());
        }
      }
      ArrayAdapter<String> searchResultAdapter =
          new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results);
      listView.setAdapter(searchResultAdapter);

      /*
       * Initializes the action of when the user selects a game from the search results. It will
       * bring the user to the game screen of the selected game.
       */
      listView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
          String item = ((TextView) view).getText().toString();
          Intent myIntent = new Intent(view.getContext(), GameView.class);
          myIntent.putExtra("gameName", item);
          startActivityForResult(myIntent, 0);
        }
      });
    }
    catch (Exception e) {
      Toast.makeText(this, "fail", Toast.LENGTH_LONG).show();
    }

    //Toast.makeText(this, gameName, Toast.LENGTH_LONG).show();
  }
}
